package com.daichi.yygh.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.daichi.yygh.common.exception.YyghException;
import com.daichi.yygh.common.helper.JwtHelper;
import com.daichi.yygh.common.result.ResultCodeEnum;
import com.daichi.yygh.enums.AuthStatusEnum;
import com.daichi.yygh.model.user.Patient;
import com.daichi.yygh.model.user.UserInfo;
import com.daichi.yygh.user.mapper.UserInfoMapper;
import com.daichi.yygh.user.service.PatientService;
import com.daichi.yygh.user.service.UserInfoService;
import com.daichi.yygh.vo.user.LoginVo;
import com.daichi.yygh.vo.user.UserAuthVo;
import com.daichi.yygh.vo.user.UserInfoQueryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    private final RedisTemplate<String, String> redisTemplate;

    private final PatientService patientService;

    @Autowired
    public UserInfoServiceImpl(RedisTemplate<String, String> redisTemplate, PatientService patientService) {
        this.redisTemplate = redisTemplate;
        this.patientService = patientService;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> loginUser(LoginVo loginVo) {
        // 校验数据
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();
        if (!StringUtils.hasLength(phone) || !StringUtils.hasLength(code)) {
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }

        // 校验手机和验证码一致性
        String redisCode = redisTemplate.opsForValue().get(phone);
        if (!code.equals(redisCode)) {
            throw new YyghException(ResultCodeEnum.CODE_ERROR);
        }

        // 如果带有openid说明必定是微信初次登录，如果有手机号不返回openid
        if (StringUtils.hasLength(loginVo.getOpenid())) {
            // 通过openid查出的账户
            UserInfo openidUser = this.getOne(new QueryWrapper<UserInfo>().eq("openid", loginVo.getOpenid()));

            // 如果没有微信注册账号，说明数据有误
            if (openidUser == null) throw new YyghException(ResultCodeEnum.DATA_ERROR);

            // 判断手机号是否已经注册过，无论何种情况，有手机号的账号才可能有操作，所以：
            // 如果没有注册过，手机号绑定到微信注册的用户中；
            // 如果注册过，把微信openid、nickname绑定到手机注册的账号，并删除这个微信注册的账号
            UserInfo phoneUser = this.getOne(new QueryWrapper<UserInfo>().eq("phone", phone));
            if (phoneUser == null) {
                openidUser.setPhone(phone);
                this.updateById(openidUser);
            } else {
                phoneUser.setOpenid(openidUser.getOpenid());
                phoneUser.setNickName(openidUser.getNickName());
                this.removeById(openidUser.getId());
                this.updateById(phoneUser);
            }

        }

        // 校验是否为新用户，如果是新用户则添加到数据库
        UserInfo userInfo = this.getOne(new QueryWrapper<UserInfo>().eq("phone", phone));
        if (userInfo == null) {
            userInfo = new UserInfo();
            userInfo.setName("");
            userInfo.setPhone(phone);
            userInfo.setStatus(1);
            this.save(userInfo);
        }

        // 校验是否被禁用
        if (userInfo.getStatus() == 0) {
            throw new YyghException(ResultCodeEnum.LOGIN_DISABLED_ERROR);
        }

        //TODO 记录登录

        //返回页面显示名称
        Map<String, Object> map = new HashMap<>();

        String name = userInfo.getName();
        if (!StringUtils.hasLength(name)) {
            name = userInfo.getNickName();
        }
        if (!StringUtils.hasLength(name)) {
            name = userInfo.getPhone();
        }
        map.put("name", name);

        String token = JwtHelper.createToken(userInfo.getId(), name);
        map.put("token", token);

        return map;
    }

    @Override
    public void userAuth(Long userId, UserAuthVo userAuthVo) {

        UserInfo userInfo = this.getById(userId);

        userInfo.setName(userAuthVo.getName());
        userInfo.setCertificatesType(userAuthVo.getCertificatesType());
        userInfo.setCertificatesNo(userAuthVo.getCertificatesNo());
        userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl());
        userInfo.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus());

        this.updateById(userInfo);

    }

    @Override
    public UserInfo getUserInfoById(Long userId) {
        UserInfo userInfo = this.getById(userId);
        userInfo.getParam().put("authStatusString", AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus()));
        return userInfo;
    }

    @Override
    public Page<UserInfo> getPageList(Page<UserInfo> page, UserInfoQueryVo userInfoQueryVo) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<UserInfo>()
                .like(StringUtils.hasLength(userInfoQueryVo.getKeyword()), "name", userInfoQueryVo.getKeyword())
                .eq(userInfoQueryVo.getStatus() != null, "status", userInfoQueryVo.getStatus())
                .eq(userInfoQueryVo.getAuthStatus() != null, "auth_status", userInfoQueryVo.getAuthStatus())
                .ge(StringUtils.hasLength(userInfoQueryVo.getCreateTimeBegin()), "create_time", userInfoQueryVo.getCreateTimeBegin())
                .le(StringUtils.hasLength(userInfoQueryVo.getCreateTimeEnd()), "create_time", userInfoQueryVo.getCreateTimeEnd());
        Page<UserInfo> userInfoPage = this.page(page, queryWrapper);
        userInfoPage.getRecords().forEach(this::packageUserInfo);
        return userInfoPage;
    }

    @Override
    public void lock(Long userId, Integer status) {
        if (status == 0 || status == 1) {
            UserInfo userInfo = this.getById(userId);
            userInfo.setStatus(status);
            this.updateById(userInfo);
        }
    }

    @Override
    public Map<String, Object> show(Long userId) {

        Map<String, Object> map = new HashMap<>();

        UserInfo userInfo = this.packageUserInfo(this.getById(userId));
        map.put("userInfo", userInfo);

        List<Patient> patientList = patientService.findAllByUserId(userId);
        map.put("patientList", patientList);

        return map;

    }

    @Override
    public void approval(Long userId, Integer authStatus) {
        if (authStatus == 2 || authStatus == -1) {
            UserInfo userInfo = this.getById(userId);
            userInfo.setAuthStatus(authStatus);
            this.updateById(userInfo);
        }
    }

    private UserInfo packageUserInfo(UserInfo userInfo) {
        userInfo.getParam().put("authStatusString", AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus()));
        userInfo.getParam().put("statusString", userInfo.getStatus() == 0 ? "锁定" : "正常");
        return userInfo;
    }
}
